package com.helei.service.Impl;

import cn.hutool.http.HttpRequest;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.helei.entity.Friend;
import com.helei.entity.Group;
import com.helei.entity.root.MessageGroup;
import com.helei.service.ApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ Author：hl
 * @ Date：2024-07-10-下午2:18
 */
@Service
@Slf4j
public class ApiServiceImpl implements ApiService {
    private static final Gson gson = new GsonBuilder()
            // 安全配置：禁止某些可能危险的类型反序列化
            // 注意：根据实际需要调整这里的配置
            .disableHtmlEscaping()
            .create();
    @Autowired
    QQProperties qqProperties;

    @Override
    public void deleteMsgAll(String groupId, String messageSeq, int i, int index) {
        List<MessageGroup> messageGroupList = get_group_msg_history(groupId, messageSeq);
        if (messageGroupList.isEmpty()) {
            return;
        }
        for (MessageGroup group : messageGroupList) {
            deleteMsg(group.getMessageId());
            log.info("i的值为::::::::{},index的值为::{}", i, index);
            i++;
            messageSeq = group.getMessageSeq();
            if (i > index) {
                return;
            }
        }
        deleteMsgAll(groupId, messageSeq, i, index);
    }

    /**
     * 获取群成员信息
     *
     * @param group_id 群号
     */
    @Override
    public boolean get_group_member_info(String group_id) {
        Map<String, String> map = new HashMap<>();
        map.put("group_id", group_id);
        map.put("user_id", qqProperties.getQq());
        String result = HttpRequest.post(qqProperties.getHttpUrl() + "/get_group_member_info")
                .body(new Gson().toJson(map))
                .timeout(20000)//超时，毫秒
                .execute().body();
        String role = new JsonParser().parse(result).getAsJsonObject().get("data").getAsJsonObject().get("role").getAsString();
        return role.equals("owner") || role.equals("admin");
    }

    /**
     * 撤回消息
     *
     * @param message_id
     */
    @Override
    public boolean deleteMsg(String message_id) {
        String aa = "{\"message_id\":" + message_id + "}";
        String result = HttpRequest.post(qqProperties.getHttpUrl() + "/delete_msg")
                .body(aa)
                .timeout(20000)//超时，毫秒
                .execute().body();
        String status = new JsonParser().parse(result).getAsJsonObject().get("status").getAsString();
        return status.equals("ok");
    }

    /**
     * 获取群消息历史记录
     *
     * @param group_id
     * @return
     */
    @Override
    public List<MessageGroup> get_group_msg_history(String group_id, String message_seq) {
        Map<String, String> map = new HashMap<>();
        map.put("group_id", group_id);
        map.put("message_seq", message_seq);
        String result = HttpRequest.post(qqProperties.getHttpUrl() + "/get_group_msg_history")
                .body(new Gson().toJson(map))
                .timeout(20000)//超时，毫秒
                .execute().body();
        JsonArray asJsonArray = new JsonParser().parse(result).getAsJsonObject().get("data").getAsJsonObject().get("messages").getAsJsonArray();
        List<MessageGroup> messageGroupList = new Gson().fromJson(new Gson().toJson(asJsonArray), new TypeToken<List<MessageGroup>>() {
        }.getType());
        return messageGroupList.stream().sorted(Comparator.comparing(MessageGroup::getMessageSeq).reversed()).collect(Collectors.toList());
    }

    @Override
    public void send_msg(String user_id, String message, String message_type, String group_id) {
        Map<String, String> map = new HashMap<>();
        map.put("message_type", message_type);
        map.put("user_id", user_id);
        map.put("message", message);
        map.put("group_id", group_id);
        String result = HttpRequest.post(qqProperties.getHttpUrl() + "/send_msg")
                .body(new Gson().toJson(map))
                .timeout(20000)//超时，毫秒
                .execute().body();
        System.out.println(result);
    }

    @Override
    public void get_image(String file) {
        Map<String, String> map = new HashMap<>();
        map.put("file", file);
        String result = HttpRequest.post(qqProperties.getHttpUrl() + "/get_image")
                .body(new Gson().toJson(map))
                .timeout(20000)//超时，毫秒
                .execute().body();
        System.out.println(result);
    }

    /**
     * 获取好友列表
     */
    @Override
    public void get_friend_list() {
        String result = HttpRequest.post(qqProperties.getHttpUrl() + "/get_friend_list")
                .timeout(20000)//超时，毫秒
                .execute().body();
        List<Friend> friendList = gson.fromJson(new JsonParser().parse(result).getAsJsonObject().get("data").getAsJsonArray().toString(), new TypeToken<List<Friend>>() {
        }.getType());
        friendList.forEach(f->{
            send_msg( f.getUserId(),"测试机器人群发消息000000000000000000", "private", null);
        });
        System.out.println(gson.toJson(friendList));
    }

    @Override
    public void get_group_list() {
       /* String result = HttpRequest.post(qqProperties.getHttpUrl() + "/get_group_list")
                .timeout(20000)//超时，毫秒
                .execute().body();*/
      /*  List<Group> friendList = gson.fromJson(new JsonParser().parse(result).getAsJsonObject().get("data").getAsJsonArray().toString(), new TypeToken<List<Group>>() {
        }.getType());
        friendList.forEach(f->{
            send_msg( null,"测试机器人群发消息000000000000000000", "group", f.getGroupId());
        });*/
        send_msg( null,"测试机器人群发消息000000000000000000", "group", "163120422");
        //System.out.println(result);
    }
}
